package cn.bugstack.domain.activity.service.armory;

import cn.bugstack.domain.activity.model.entity.ActivitySkuEntity;
import cn.bugstack.domain.activity.repository.IActivityRepository;
import cn.bugstack.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: Zchy
 * @Description: 活动sku预热
 * @DateTime: 12/1/2024 3:54 PM
 **/
@Slf4j
@Service
public class ActivityArmory implements IActivityArmory, IActivityDispatch {

    @Resource
    private IActivityRepository repository;

    @Override
    public boolean assembleActivitySku(Long sku) {
        //预热sku库存
        ActivitySkuEntity activitySkuEntity = repository.queryActivitySku(sku);
        cacheActivitySkuStock(sku, activitySkuEntity.getStockCount());

        //预热活动【查询的同时进行预热】
        repository.queryRaffleActivityByActivityId(activitySkuEntity.getActivityId());

        //预热活动次数【查询的同时进行预热】
        repository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        return true;
    }

    @Override
    public boolean assembleActivitySkuByActivityId(Long activityId) {
        List<ActivitySkuEntity> activitySkuEntities = repository.queryActivitySkuListByActivityId(activityId);
        for (ActivitySkuEntity activitySkuEntity : activitySkuEntities) {
            cacheActivitySkuStock(activitySkuEntity.getSku(), activitySkuEntity.getStockCount());
            //预热活动次数【查询的同时进行预热】
            repository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        }
        //预热活动【查询的同时进行预热】
        repository.queryRaffleActivityByActivityId(activityId);
        return true;
    }

    private void cacheActivitySkuStock(Long sku, Integer stockCount) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        repository.cacheActivitySkuStock(cacheKey, stockCount);
    }

    @Override
    public boolean subtractionActivitySkuStock(Long sku, Date endDateTime) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        return repository.subtractionActivitySkuStock(cacheKey, sku, endDateTime);
    }
}
